import asyncio

#用协程实现一个计算平均数的函数

def my_average():
    total = 0
    number = 0
    while True:
        try:
            value = yield total/number
        except ZeroDivisionError:
            value = yield 0
        total += value
        number += 1

my_avg = my_average()
next(my_avg)
while True:
    i = int(input("please enter one value："))
    print("Average is：", my_avg.send(i))


#编写一个asyncio异步程序

class Response:
    staus_code = 200

async def sim_request(index):
    print(f"模拟发送请求 index：{index}")
    response = Response()
    await asyncio.sleep(1)
    print(f"request index {index}, response staus_code:{response.staus_code}")
    return response.staus_code

loop = asyncio.get_event_loop()

task_array = []
for i in range(30):
    task_array.append(sim_request(i))

loop.run_until_complete(asyncio.wait(task_array))

loop.close

from threading import Thread, Lock
from multiprocessing import Process, Lock, Queue

def save_file(index, lock):
    with lock:
        with open("test.log", "a", encoding="utf-8") as f:
            f.write(str(index) + "\n")

def save_queue(index, my_queue):
    my_queue.put(index)

def foo():
    global zero
    for i in range(10**5):
        with lock:
            zero += 1
            zero -= 1


if __name__ == "__main__":

#多线程锁
    zero = 0
    thread_array = []
    lock = Lock()
    for i in range(2):
        t = Thread(target=foo)
        thread_array.append(t)
        t.start()
    for t in thread_array:
        t. join()
    print(zero)


#多进程锁
    process_array = []
    lock = Lock()
    for i in range(10):
        p = Process(target=save_file, args=(i, lock))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()
    print("done")

#多进程通过Queue来实现进程通信
    process_array = []
    my_queue = Queue()
    for i in range(10):
        p = Process(target=save_queue, args=(i, my_queue))
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()

    for i in range(10):
        print(my_queue.get())